package com.yq.tanhua.im

import android.app.Application
import com.fmt.mvi.learn.gobal.log
import com.hyphenate.EMCallBack
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMConversation
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMOptions
import kotlinx.coroutines.suspendCancellableCoroutine
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine


/**
 * @author: user
 * @date: 2023/4/24
 */
@Singleton
open class HxImFunction @Inject constructor() : ImFunction {

    override fun testhilt() {
        "测试代码，测试Hilt 自动注入 当前对象地址是：${this}".log()
    }


    override fun init(application: Application) {
        //初始化im
        val options = EMOptions()
        options.setAppKey("1127230418172669#tanhua");
        EMClient.getInstance().init(application, options);
    }


    override fun login(userName: String, userPsw: String, result: EMCallBack) {
        EMClient.getInstance().login(userName, userPsw, result)
    }

    override fun loginOut() {
        EMClient.getInstance().logout(true)
    }

    override fun preLoadData() {
        //确保进入主页面后本地会话和群组均加载完毕。
        EMClient.getInstance().chatManager().loadAllConversations()
        EMClient.getInstance().groupManager().loadAllGroups()
    }


    override suspend fun getAllConversations(): MutableMap<String, EMConversation>? {
        return  suspendCoroutine { coroutine->
            EMClient.getInstance().chatManager().asyncFetchConversationsFromServer(object :EMValueCallBack<Map<String, EMConversation>>{
                override fun onSuccess(value: Map<String, EMConversation>?) {
                    coroutine.resume(value as MutableMap<String, EMConversation>)
                }

                override fun onError(error: Int, errorMsg: String?) {
                    coroutine.resumeWithException(Exception(errorMsg))
                }

            })
        }
    }

    override fun sendTextMsg(content: String, toUserId: String, emCallBack: EMCallBack) {
        val createTextSendMessage = EMMessage.createTextSendMessage(content, toUserId)
        createTextSendMessage.setMessageStatusCallback(emCallBack)
        EMClient.getInstance().chatManager().sendMessage(createTextSendMessage)
    }

}